import Vue from 'vue'
import axios from 'axios'
// import store from '@/store'
import { VueAxios } from './axios'
import { Notification } from 'element-ui'
// import { ACCESS_TOKEN } from '@/store/mutation-types'

const baseURL = process.env.API_ROOT
// 创建 axios 实例
const service = axios.create({
  baseURL: baseURL, // api base_url
  timeout: 6000 // 请求超时时间
})
export const pureAxios = axios.create({
  baseURL: baseURL, // api base_url
  timeout: 6000 // 请求超时时间
})

const err = (error) => {
  if (error.response) {
    const data = error.response.data
    // const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      Notification.error({
        title: data.msg + 1
      })
    }
    if (error.response.status === 500) {
      Notification.error({
        title: data.msg + 2
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      Notification.error({
        title: 'Authorization verification failed'
      })
      // if (token) {
      //   store.dispatch('Logout').then(() => {
      //     setTimeout(() => {
      //       window.location.reload()
      //     }, 1500)
      //   })
      // }
    }
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  // const token = Vue.ls.get(ACCESS_TOKEN)
  // if (token) {
  //   config.headers['token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  // }
  return config
}, err)

pureAxios.interceptors.request.use(config => {
  // const token = Vue.ls.get(ACCESS_TOKEN)
  // if (token) {
  //   config.headers['token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  // }
  return config
}, err)

// response interceptor
service.interceptors.response.use((res) => {
  // console.log("xsds",res)
  let data = res.data || ''
  let code = data.code || ''
  // console.log("xsds",code)
  if (code == '') {
    if (code !== 0) {
      let msg = data.msg || ''
      if (msg != '') {
        Notification.error({
          title: msg + 3
        })
      }
      return Promise.reject('error')
    }
  } else {
    return data
  }
}, err)


const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
